<template>
  <page-dialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-list="dialogInfo.btList"
  >
    <!-- 条件栏 -->
    <NewPageFilter
      :query="filterInfo.query.queryMap"
      :query-more-json="true"
      :filter-list="filterInfo.searchList"
      :filter-btn="filterInfo.searchBtn"
    >
      <template v-slot:filter-supplierProdct>
        <slip-select
          v-model="filterInfo.query.queryParams.notDefaultProductSupplierId"
          value-key="value"
          placeholder="选择供货供应商"
          :api="supplierInfo.api"
          :query="supplierInfo.query"
          key-field="supplierName"
          value-field="supplierId"
          :clearable="true"
          :filterable="true"
          :multiple="true"
          @change="search"
        />
      </template>
      <template v-slot:filter-fill>
        <el-checkbox
          v-model="filterInfo.data.fill"
          label="只显示领出仓库可用数量>0产品"
          border
          @change="changeCheck"
        ></el-checkbox>
      </template>
    </NewPageFilter>
    <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
      <dialog-table
        ref="resourceTable"
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-key="rowKey"
        :highlight-row="highlightRow"
        :checked-row-list="checkedRowList"
        :reserve-selection="true"
        :check-box="checkBox"
        :selectable="selectable"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-editQty="scope">
          <el-form-item
            v-if="scope.row.qtyOperateMode !== 3"
            class="margin-bottom"
            @click.stop=""
          >
            <div class="page-table-input-number-wrapper">
              <div class="page-table-input-number-left">
                <div class="page-table-input-number-item">
                  <el-form-item>
                    <el-input-number
                      v-model.lazy="scope.row.largeUnitQty"
                      style="width: 100%; margintop: 18px"
                      clearable
                      controls-position="right"
                      :precision="
                        scope.row.qtyOperateMode === 0 ||
                        scope.row.qtyOperateMode === 2
                          ? 0
                          : state.systemConfig.qty_show_precision
                      "
                      :min="0"
                      :max="99999999"
                    />
                  </el-form-item>
                  <div class="page-table-input-number-item-unite">
                    {{ scope.row.unitName }}
                  </div>
                </div>
                <div
                  v-if="
                    scope.row.unitConvertCoefficient > 1 &&
                    scope.row.qtyOperateMode === 2
                  "
                  class="page-table-input-number-item"
                >
                  <el-form-item>
                    <el-input-number
                      v-model.lazy="scope.row.smallUnitQty"
                      style="width: 100%; margintop: 18px"
                      clearable
                      controls-position="right"
                      :precision="0"
                      :min="0"
                      :max="scope.row.unitConvertCoefficient - 1"
                    />
                  </el-form-item>
                  <div class="page-table-input-number-item-unite">
                    {{ scope.row.calcUnitName }}
                  </div>
                </div>
              </div>
              <div class="page-table-input-number-right">
                {{ $fn.qtyFormatter(scope.row.editQty) }}
              </div>
            </div>
          </el-form-item>
          <span v-else>{{ $fn.qtyFormatter(scope.row.editQty) }}</span>
        </template>
      </dialog-table>
    </el-form>
  </page-dialog>
</template>
<script setup name="SelectProductWithStockQty">
import PageDialog from '../PageDialog/index'
import DialogTable from '../DialogTable/index'
import NewPageFilter from '../NewPageFilter/index'
import SlipSelect from '../SlipSelect/index'
import { getCustomizeSetting } from '@/api/customize'
import { getProductWithOtherCustomizeList, getSupplierAll } from '@/api/core.js'
import utils from '@/common/js/utils'
import { watch } from 'vue'

const { proxy } = getCurrentInstance()
const emit = defineEmits(['update', 'callback', 'reset'])
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: false,
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  rowKey: {
    type: String,
    default: 'id',
  },
  api: {
    type: Function,
    default: getProductWithOtherCustomizeList,
  },
  showDialog: {
    type: Boolean,
    default: false,
  },
  showPrice: {
    type: Boolean,
  },
  showSupplierName: {
    type: Boolean,
    default: false,
  },
  notDefaultProductSupplier: {
    //是否供货供应商赛选
    type: Boolean,
    default: true,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  queryParams: {
    type: Object,
    default: function () {
      return {}
    },
  },
  showStock: {
    type: Boolean,
    default: false,
  },
  tableKey: {
    type: String,
    default:
      'productPageWithDefaultSupplier-com.slip.spd.entity.vo.core.CoreProductVONew',
  },
  checkedList: {
    type: Array,
    default: () => {
      return []
    },
  },
  checkedRowList: {
    type: Array,
    default: () => {
      return []
    },
  },
  saveEmpty: {
    type: Boolean,
    default: false,
  },
  showCheckBox: {
    //只显示领出仓库可用数量>0产品 checkbox框
    type: Boolean,
    default: false,
  },
  allowUseQtyGreaterStock: {
    type: String,
    default: '',
  },
})

const supplierInfo = reactive({
  api: getSupplierAll,
  query: {
    supplierAuth: 'supplierId',
    sort: 'create_time desc',
  },
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    page: true,
    customizeUserVO: {},
    sortString: proxy.sortString,
    queryMap: {
      type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      exportStockQty: {
        queryType: 'NOT_IN',
        value: null,
      },
    },
    queryParams: {},
  },
  data: {
    fill: false,
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'slot', value: 'fill', show: props.showCheckBox },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  fieldList: [],
})
// 弹窗相关
const dialogInfo = reactive({
  title: '选择产品',
  width: '90%',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      disabled: !props.saveEmpty,
      event: save,
      show: true,
    },
  ],
})
const state = reactive({
  systemConfig: proxy.$store.state.permission.systemConfig,
  selectRow: [],
})
const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emit('update:showDialog', newValue) // 更新父组件shows
  },
})
watch(
  () => tableInfo.data,
  (val) => {
    tableInfo.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let editCalcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let editQty = proxy.$fn.qtyFormatter(
        proxy.$fn.accDiv(editCalcQty, unitConvertCoefficient)
      )
      row['editCalcQty'] = editCalcQty
      row['editQty'] = editQty
      row.sumAmount = proxy.$fn.accMul(
        proxy.$fn.accAdd(
          proxy.$fn.accDiv(smallUnitQty, unitConvertCoefficient),
          largeUnitQty
        ),
        parseFloat(row.price)
      )
    })
  },
  {
    deep: true,
  }
)
watch(
  () => props.allowUseQtyGreaterStock,
  (val) => {
    if (val == '0' && props.showCheckBox) {
      filterInfo.data.fill = true
      filterInfo.query.queryMap.exportStockQty.value = 0
    } else {
      filterInfo.data.fill = false
      filterInfo.query.queryMap.exportStockQty.value = null
    }
  },
  {
    deep: true,
    immediate: true,
  }
)

let obj = {
  price: {
    label: '单价',
    value: 'price',
    hidden: true,
    type: 'column',
    show: false,
    permission: !props.showPrice,
    formatter: proxy.$fn.TripartiteMethod,
  },
  storeStockQty: {
    label: '领入仓库可用数量',
    value: 'storeStockQty',
    hidden: true,
    type: 'column',
    formatter: utils.qtyFormatter,
    componentType: 'number',
    show: false,
  },
  exportStockQty: {
    label: '领出仓库可用数量',
    value: 'exportStockQty',
    hidden: true,
    type: 'column',
    formatter: utils.qtyFormatter,
    componentType: 'number',
    show: false,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !props.showPrice,
    show: false,
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  showPrice: {
    label: '展示价格',
    value: 'showPrice',
    type: 'column',
    show: false,
    permission: !props.showPrice,
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  editQty: {
    label: '数量',
    value: 'editQty',
    type: 'slot',
    componentType: 'number',
    show: false,
    hidden: true,
    minWidth: '250px',
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
function selectable(row, index) {
  let allow_use_qty_greater_stock =
    systemConfig.value.allow_use_qty_greater_stock
  if (allow_use_qty_greater_stock == 0) {
    return row.exportStockQty > 0 ? true : false
  }
  return true
}
function changeCheck(type) {
  //【领用申请】新增领用申请单-选择产品 页面 增加一个checkbox框 只显示领出仓库可用数量>0产品
  if (type) {
    filterInfo.query.queryMap.exportStockQty.value = 0
  } else {
    filterInfo.query.queryMap.exportStockQty.value = null
  }
  search()
}
// 获取列表
function getList() {
  tableInfo.refresh = Math.random()
}
function search() {
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
function save() {
  state.selectRow.forEach((item) => {
    item['calcQty'] = item.editCalcQty
    item['qty'] = item.editQty
  })
  handleClose()
  emit('callback', state.selectRow)
}
function handleEvent(event, data) {
  switch (event) {
    case 'list':
      let allow_use_qty_greater_stock =
        systemConfig.value.allow_use_qty_greater_stock
      if (allow_use_qty_greater_stock == 0) {
        if (data.length) {
          data.forEach((item) => {
            item.disabled = item.exportStockQty > 0 ? false : true
          })
        }
        tableInfo.data = data
      }
      break
    case 'tableClickRow':
      state.selectRow = data
      if (!props.saveEmpty) {
        dialogInfo.btList[1].disabled = !state.selectRow
      }
      break
    case 'tableCheck':
      state.selectRow = data
      if (!props.saveEmpty) {
        dialogInfo.btList[1].disabled = !state.selectRow
      }
      break
  }
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emit('reset')
}
function getCustomize() {
  let param = { tableKey: props.tableKey }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      let supplierProdct = {
        slot: true,
        value: 'supplierProdct',
      }
      if (props.notDefaultProductSupplier) {
        filterInfo.searchList = searchInfo.searchList.concat(supplierProdct)
      } else {
        filterInfo.searchList = searchInfo.searchList
      }
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })

      filterInfo.query.customizeUserVO = data
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...props.query,
        ...filterInfo.query.queryMap,
      }
      filterInfo.query.queryParams = {
        ...filterInfo.query.queryParams,
        ...props.queryParams,
      }
      tableInfo.api = props.api
      getList()
    }
  })
}
</script>

<style scoped lang="scss"></style>
